package rgbos.forum.webClient;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Vector;

import rgbos.forum.domain.Post;
import rgbos.forum.domain.Topic;
import rgbos.forum.exceptions.UserExeception;
import jaxcent.HtmlDiv;
import jaxcent.HtmlElement;
import jaxcent.HtmlInputButton;
import jaxcent.HtmlPara;
import jaxcent.HtmlTable;
import jaxcent.JaxcentPage;
import jaxcent.Jaxception;
import jaxcentServer.ServerMain;

public class ShowTopics extends jaxcent.JaxcentPage {

	private HtmlPara para_ = new HtmlPara(this,"table");
	private HtmlPara footpara_ = new HtmlPara(this,"footerPara");
	private HtmlTable table_ = new HtmlTable(this,"topicsTable");
	private HtmlDiv container_ = new HtmlDiv(this, "hideThis");
	private DateFormat df_ = new SimpleDateFormat("dd/MM/yyyy");	
	private WebClientHandler handler_ = WebClientHandler.getWebClientHandler();
	private String author_;
	private boolean flag = false;
	
	public ShowTopics() {
		super();
	}
	
	protected void onUnload() {
		try {
			Map sessionData = getAllSessionData(false);
			handler_.unload(sessionData);			
		} catch (Jaxception e) {
			e.printStackTrace();
		}
	}
	
	protected void onLoad() {
		try {
			container_.setStyle("display", "none");
			setFormSaveEnabled(false);
			Map sessionData = getAllSessionData( false );
			this.author_ = (String)sessionData.get("uName");			
			handler_.DisplayHeader(para_, sessionData, this); //must be before display footer!
			handler_.displayFooter(footpara_, sessionData, this);
			String permissions = handler_.getClientType(sessionData);
			Vector<Topic> topics = handler_.getControl().showNewTopics();
							
			HtmlElement[] delTopicLink= new HtmlElement[topics.size()];
			HtmlElement[] editTopicLink= new HtmlElement[topics.size()];
			
			final String tPath = getCurrentPath();
			final int tIndex = tPath.indexOf("page=");
			int from = 0;
			int to = topics.size();
			if (tIndex != -1) {
				final int pageNumber = Integer.valueOf(tPath.substring(tIndex+5));
				if (pageNumber >= 0) {
					from = pageNumber * 15;
					to = Math.min(from+15, topics.size());
				}				
			}
			Collections.sort(topics);
			for (int i = from; i < to; i++) {				
				final int index = i;
				final Topic top = topics.get(i);
				String delete="<a id=\"delTopic"+top.getId_()+"\" href=\"\" onClick=\"return false;\">Delete</a>";
				String edit="<a id=\"editTopic"+top.getId_()+"\" href=\"\" onClick=\"return false;\">Edit</a>";
				String title = "<a href=\"showPosts.html?topicId=" + top.getId_() + "\">" + handler_.unescape(top.getTitle_()) + "</a>";
				if(permissions.contentEquals("Moderator") || permissions.contentEquals("Admin")){
					String[] row = {title+" | "+edit+" | "+delete,top.getAuthorName(),df_.format(top.getCreationDate_()),
							String.valueOf(top.getPostCount()),String.valueOf(top.getViewCount())};
					table_.insertRow(i+1,row);	
					delTopicLink[i] = new HtmlElement(this, "delTopic"+top.getId_()) {
						protected void onClick( Map pageData ) {							
							try {
								boolean sure = showConfirmDialog("Are you sure you want to delete this topic?");
								if (sure) {						
									handler_.getControl().deleteTopic(top.getId_());
									navigate("/showTopics.html");
								}
							}
							catch (Jaxception e1) {
								e1.printStackTrace();
							}
						}
					};
					editTopicLink[i] = new HtmlElement(this, "editTopic"+top.getId_()) {
						protected void onClick( Map pageData ) {
								try {
									String newName = showInputDialog("Enter new name", handler_.unescape(top.getTitle_()));
									newName = handler_.escape(newName);
									if(newName.equals("")){
										showMessageDialog("You can't choose empty title");
										return;
									}else if(newName.equals(handler_.escape(top.getTitle_()))){
										return;
									}
									
									Topic newTop = new Topic(top.getId_(),newName,top.getAuthorName(),top.getCreationDate_(),top.getPostVector(),top.getPostCount(),top.getViewCount());
									handler_.getControl().modifyTopic(newTop);
									navigate("/showTopics.html");
								} catch (Jaxception e1) {
									e1.printStackTrace();
								}
							try {
								navigate("/showTopics.html");
							} catch (Jaxception e) {
								e.printStackTrace();
							}
						}
					};

					
					
				}else{
					String[] row = {title,top.getAuthorName(),df_.format(top.getCreationDate_()),
							String.valueOf(top.getPostCount()),String.valueOf(top.getViewCount())};
					table_.insertRow(i+1,row);	
				}
			}
			
			if (permissions.contentEquals("User") | permissions.contentEquals("Moderator")
					| permissions.contentEquals("Admin")) {
				HtmlPara showLinkPara = new HtmlPara(this, "bottom");
				showLinkPara.setInnerHTML("<a id=\"newTopicLink\" href=\"\" onClick=\"return false;\">Add New Topic</a>");
				final JaxcentPage page = this;
				HtmlElement newTopicLink = new HtmlElement(this, "newTopicLink") {
					protected void onClick( Map pageData ) {
						HtmlTable addNewTopicTable = new HtmlTable(page, "newTopicTable");
						try {
							if (addNewTopicTable.getStyle("display").contentEquals("none")) {								
								addNewTopicTable.setStyle("display", "block");
							}
							else {
								addNewTopicTable.setStyle("display", "none");
							}
						} catch (Jaxception e) {
							e.printStackTrace();
						}
					}
				};
				
				HtmlInputButton newTopicButton = new HtmlInputButton(this, "newMessSubmit") {
					protected void onClick( Map pageData ) {							
						try {
							if (flag)
								return;
							flag = true;
							String title = handler_.escape((String) pageData.get("title"));
							String body = handler_.escape((String) pageData.get("body"));							 
							if(title.equals("")){
								showMessageDialog("You can't open a new topic without a title");
								flag = false;
								return;
							}
							if(body.equals("")){
								showMessageDialog("You can't open a new topic without a body");
								flag = false;
								return;
							}
							Date currentDate = Calendar.getInstance().getTime();
							Topic tNewTopic = new Topic(0, title, author_, currentDate, new Vector<Integer>(), 0, 0);			
							Post tNewPost = new Post(0, title, author_, currentDate, body);
							int topicId = handler_.getControl().addNewTopic(tNewTopic);
							handler_.getControl().addNewPost(tNewPost, topicId);
							navigate("/showPosts.html?topicId="+topicId);
						} catch (Jaxception e) {
							e.printStackTrace();
						}
						flag = false;
					}
				};
				
				newTopicButton.setValue("Add New Topic");
			}
			container_.setStyle("display", "block");
		} catch (Jaxception e) {
			e.printStackTrace();
		}		
	}
}
